package cn.datastruct.four;
/*
    总结：
        1，要把思路捋清楚，有一点不明确就会出bug
        2,add,del这两个函数比较容易写错，要多敲几遍
        3，
* */
//定义小孩类，属性，构造器
class kid {
    public int age;
    public String name;
    public kid next;

    public kid(int age, String name) {
        this.age = age;
        this.name = name;
    }
    //重写toString()

//    @Override
//    public String toString() {
//        return "kid{" +
//                "age=" + age +
//                ", name='" + name + '\'' +
//                ", next=" + next +
//                '}';
//    }


    @Override
    public String toString() {
        return "kid{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

//定义一个约瑟夫环
/*
    1，求链表长度
    2、实现add(DoubleLinkedNode dln)函数
    3、实现del()函数
    4、insert(DoubleLinkedNode dln, int index),删除指定位置元素
    5，show(),打印链表
* */
public class CricleLinkedList {
    public kid first;//一直指向第一个


    //成员函数
    //1，求链表长度
    public int length() {
        if (this.first == null)
            return 0;
        kid temp = this.first.next;
        if (temp == this.first)
            return 1;
        int length = 1;
        while (temp != this.first) {
            temp = temp.next;
            length++;
        }
        return length;
    }

    //2、实现add(DoubleLinkedNode dln)函数
    public boolean add(kid d) {
        boolean flag = false;
        //判断是不是第一个
        if (this.first == null) {
            this.first = d;
            this.first.next = this.first;
            flag = true;
        } else {
            //设置一个临时节点
            kid temp = this.first;
            while (!flag) {
                if (temp.next == this.first) {
                    flag = true;
                    break;
                }
                temp = temp.next;
            }
            d.next = temp.next;
            temp.next = d;
        }
        return flag;
    }

    //3、实现del()函数
    public void del(int k) {
        int length = this.length();
        if (length == 0)
            return;
        kid temp = this.first;
        //移动到最后一个位置
        for (int i = 0; i < length - 1; i++) {
            temp = temp.next;
        }

        //删除节点
        while (temp != temp.next) {
            for (int i = 0; i < k -1 ; i++) {
                temp = temp.next;
            }
            System.out.println(temp.next);
            temp.next = temp.next.next;//删除一个元素

        }
        this.first = null;
        System.out.println(temp);


    }

    //5，show(),打印链表
    public void show() {
        int length = this.length();
        if (length == 0) {
            System.out.println("此链表为空");
            return;
        }
        kid temp = this.first;
        while (temp.next != this.first) {
            System.out.println(temp);
            temp = temp.next;
        }
        System.out.println(temp);
        return;
    }
}
